package com.workspace.js_website.config.authentication;

import com.workspace.js_website.config.FailureHandler;
import com.workspace.js_website.config.SuccessHandler;
import com.workspace.js_website.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 把过滤器和校验器配置进去
 */

@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final UserService userService;
    private final SuccessHandler successHandler;
    private final FailureHandler failureHandler;
    private final ValidateCodeFilter validateCodeFilter;
    private final SmsCodeAuthenticationFilter smsCodeAuthenticationFilter;
    private final SmsCodeAuthenticationProvider smsCodeAuthenticationProvider;

    @Autowired
    public SmsCodeAuthenticationSecurityConfig(UserService userService,
                                               SuccessHandler successHandler,
                                               FailureHandler failureHandler,
                                               ValidateCodeFilter validateCodeFilter) {
        this.userService = userService;
        this.successHandler = successHandler;
        this.failureHandler = failureHandler;
        this.validateCodeFilter = validateCodeFilter;
        smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
    }

    @Override
    public void configure(HttpSecurity http) {
        //SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(failureHandler);

        // 获取验证码提供者
        //SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(userService);

        // 将短信验证码校验器注册到 HttpSecurity， 并将短信验证码过滤器添加在 UsernamePasswordAuthenticationFilter 之前
        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
